//
// Created by sgyt on 2020/4/3.
// 读写锁
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

void *pthread_write(void *arg);
void *pthread_read(void *arg);

int total = 100;
int count = 0;
pthread_rwlock_t rwlock;

int main(int argc,char *argv[])
{
    int i = 0;
    int res;
    void *resval;
    pthread_t pthread[8];

    //初始化读写锁
    pthread_rwlock_init(&rwlock,NULL);

    //创建线程一
    for(i = 0;i<4;i++)
    {
        res = pthread_create(&pthread[i],NULL,pthread_write,NULL);
        if(res != 0)
        {
            perror("pthread_create is error\n");
            exit(EXIT_FAILURE);
        }
    }


    //创建线程二
    for(i = 4;i<8;i++)
    {
        res = pthread_create(&pthread[i],NULL,pthread_read,NULL);
        if(res != 0)
        {
            perror("pthread_create is error\n");
            exit(EXIT_FAILURE);
        }
    }


    //等待线程结束
    for(int i =0;i<8;i++)
    {
        pthread_join(pthread[i],&resval);
    }
    pthread_rwlock_destroy(&rwlock);
    return 0;
}

void *pthread_write(void *arg)
{
    while(1)
    {
        //加入写锁
        pthread_rwlock_wrlock(&rwlock);
        printf("w-[%d]\n",count);
        count++;
        //释放写锁
        pthread_rwlock_unlock(&rwlock);
        sleep(2);
    }

}

void *pthread_read(void *arg)
{
    while(1)
    {
        //加入读锁
        pthread_rwlock_rdlock(&rwlock);
        printf("r-[%d]\n",count);
        //释放读锁
        pthread_rwlock_unlock(&rwlock);
        sleep(2);
    }

}
